package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzNotEmptyException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult findAll(ClazzQueryParam c) {
        PageHelper.startPage(c.getPage(), c.getPageSize());
        List<Clazz> rows = clazzMapper.findAll(c);
        LocalDate date = LocalDate.now();
        rows.forEach(clazz -> {
                if(date.isBefore(clazz.getBeginDate())){
                    clazz.setStatus("未开班");
                }else if(date.isBefore(clazz.getEndDate())){
                    clazz.setStatus("已开班");
                }else{
                    clazz.setStatus("已结课");
                }
        });
        Page<Clazz> p = (Page<Clazz>) rows;

        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        int studentCount = studentMapper.countStudentsByClassId(id);
        if(studentCount > 0){
            throw new ClazzNotEmptyException();
        }else{
            clazzMapper.deleteById(id);
        }

    }

    @Override
    public void insertClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insertClazz(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    @Override
    public void update(Clazz c) {
        c.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(c);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }
}
